package com.github.shiqiyue.myadmin.config.mybatis.plus;

import java.util.Date;

import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.mapper.MetaObjectHandler;

/****
 * 自定义公共字段填充
 *
 * @author wwy
 *
 */
@Component
public class CustomMetaObjectHandler extends MetaObjectHandler {
	
	private static final String ADD_DATE = "addDate";
	
	private static final String EDIT_DATE = "editDate";
	
	private static final String VERSION = "version";
	
	private static final Long DEFAULT_VERSION = 1L;
	
	private static final Long VERSION_STEP = 1L;
	
	@Override
	public void insertFill(MetaObject metaObject) {
		Date now = new Date();
		Object addDate = getFieldValByName(ADD_DATE, metaObject);
		if (addDate == null) {
			setFieldValByName(ADD_DATE, now, metaObject);
		}
		Object editDate = getFieldValByName(EDIT_DATE, metaObject);
		if (editDate == null) {
			setFieldValByName(EDIT_DATE, now, metaObject);
		}
		Object version = getFieldValByName(VERSION, metaObject);
		if (version == null) {
			setFieldValByName(VERSION, DEFAULT_VERSION, metaObject);
		}
	}
	
	@Override
	public void updateFill(MetaObject metaObject) {
		setFieldValByName(EDIT_DATE, new Date(), metaObject);
		// Object version = getFieldValByName(VERSION, metaObject);
		// if (version != null) {
		// setFieldValByName(VERSION, Long.parseLong(version.toString()) +
		// VERSION_STEP, metaObject);
		// }
	}
	
}